/*
 * 
 * When the client is sending will say the length of the file 
 * that is going to be send 
 * Also should set a timeout on a packet when recieving
 * 
 * 
 */

package udpserver;

import java.net.*;


/**
 *
 * @author makkalot
 */
public class VideoServer extends GeneralUdpServer{

    public final static int DEFAULT_PORT = 9999;
    private boolean to_stop = true; //when to stop that madness 
    //here we will copy the stuff
    
    private SaveImage save_video; 

    public VideoServer ()throws SocketException{
        super(DEFAULT_PORT);
        System.out.println("I start listening on port : "+VideoServer.DEFAULT_PORT);
    }
    
    @Override
    public void respond(DatagramPacket packet) {
    
        //copy here
        byte[] data = new byte[packet.getLength()];
        System.arraycopy(packet.getData(), 0, data, 0, packet.getLength());
        
        try{
            String temp_str = new String(packet.getData(), 0, packet.getLength());
            temp_str=temp_str.trim(); //remove the white spaces
            
            //System.out.println("The string we recieved is "+temp_str);
            if (temp_str.equals("stop")==true){
                this.to_stop = true;
                
                //close the file and free it please
                if(this.save_video!=null){
                this.save_video.finishWriting();
                this.save_video = null;
                
                System.out.println("I got all chunks closing the store ");
                }
            }
            else if(temp_str.equals("start")==true){
                this.to_stop = false;
                //here open the file to write
                this.save_video = new SaveImage();
                System.out.println("I start recieving videos");
            }
            
            if(!to_stop){
                System.out.println("We got a packet from " + packet.getAddress() + 
                "the length is :" +packet.getLength());
                this.save_video.writeThatByte(data,packet.getLength());
            }
            
        
        }
        
        
        
        catch (Exception ex) {
        // This shouldn't happen impossible error :)
            System.out.println("We didnt get a string sorry");
        }
        
    }
    
    public static void main(String[] args){
    
        //make an instance for it ...
        try{
            VideoServer vs = new VideoServer();
            vs.start(); //start the thread
                
        }
        catch(SocketException e){
            System.err.println("Something bad happened here ...");
        }
        
    }

}
